﻿using Capstone.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;
using Capstone.Views;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Capstone.ViewModels
{
    public class NewItemViewModel : BaseViewModel
    {
        private Item _selectedItem;
        public ObservableCollection<Item> Diary_Items { get; }
        public Command LoadItemsCommand { get; }
        public Command AddItemCommand { get; }
        public Command<Item> ItemTapped { get; }
        public NewItemViewModel()
        {
            Title = "New diary";
            Diary_Items = new ObservableCollection<Item>();
            LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());

            ItemTapped = new Command<Item>(OnItemSelected);


        }

        async Task ExecuteLoadItemsCommand()
        {
            IsBusy = true;

            try
            {
                Diary_Items.Clear();
                var diary_items = await DiaryDataStore.GetDiaryItemsAsync(true);
                foreach (var diary_item in diary_items)
                {
                    Diary_Items.Add(diary_item);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }

        public void OnAppearing()
        {
            IsBusy = true;
            SelectedItem = null;
        }

        public Item SelectedItem
        {
            get => _selectedItem;
            set
            {
                SetProperty(ref _selectedItem, value);
                OnItemSelected(value);
            }
        }


        async void OnItemSelected(Item diary_item)
        {
            if (diary_item == null)
                return;

            // This will push the ItemDetailPage onto the navigation stack
            if (diary_item.Id == "Gut_Symptom_Diary")
                await Shell.Current.GoToAsync($"{nameof(GutSymptomDiaryPage)}?{nameof(GutSymptomDiaryViewModel.ItemId)}={diary_item.Id}");


            if (diary_item.Id == "Stool_Quality_Diary")
                await Shell.Current.GoToAsync($"{nameof(StoolQualityDiaryPage)}?{nameof(StoolQualityDiaryViewModel.ItemId)}={diary_item.Id}");
        }


        //private async void OnCancel()
        //{
        //    // This will pop the current page off the navigation stack
        //    await Shell.Current.GoToAsync("..");
        //}



        }
    }